package dk.eal.kbr.mule.component.exchange;

import java.util.Date;

import microsoft.exchange.webservices.data.Appointment;
import microsoft.exchange.webservices.data.ConflictResolutionMode;
import microsoft.exchange.webservices.data.DeleteMode;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ItemId;
import microsoft.exchange.webservices.data.MessageBody;
import microsoft.exchange.webservices.data.SendInvitationsMode;

public class UpdateCalenderItem extends ExchangeProxy {

	@Override
	public ExchangeCalenderItem doWork(ExchangeCalenderItem calenderItem)
			throws Exception {

		try {
			Appointment appointment = updateAppointment(calenderItem);
			calenderItem.exchangeItemId = appointment.getId().getUniqueId();
			calenderItem.setIsActive(1);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace(); // Test kode
			throw new Exception(e);
		}

		return calenderItem;
	}

	public Appointment updateAppointment(ExchangeCalenderItem externalData)
			throws Exception {

		Appointment appointment;

		ExchangeService service = connect(externalData.email,
				externalData.password);
		ItemId id = new ItemId(externalData.exchangeItemId);
		appointment = Appointment.bind(service, id);
		
		//appointment.delete(DeleteMode.HardDelete);

		//appointment = new Appointment(service);

		appointment.setSubject(externalData.getSubject());
		appointment.setBody(MessageBody
				.getMessageBodyFromText(externalData.getBody()));


		Date startDate = externalData.getStartTimestamp(); // formatter.parse("2012-06-19 12:00:00");
		Date endDate = externalData.getEndTimestamp();// formatter.parse("2012-06-19 13:00:00");
		appointment.setStart(startDate);// new Date(2010-1900,5-1,20,20,00));
		appointment.setEnd(endDate); // new Date(2010-1900,5-1,20,21,00));
		appointment.getRequiredAttendees().clear();

		appointment.update(ConflictResolutionMode.AlwaysOverwrite);

		return appointment;

	}

	/*
	 * private boolean isEquale(ExchangeCalenderItem externalData, Appointment
	 * appointment) { // TODO Auto-generated method stub return false; }
	 */

}
